# -*- coding: utf-8 -*-
import gobject
import aspects
import dl
# NOTIFICATION START
import gtk
import desktop

try:
    import pynotify
    if not pynotify.init("emesene"):
        raise
except:
    ERROR = _('there was a problem initializing the pynotify module')
#NOTIFICATION STOP


class kiduxPluginCore:
    def __init__(self, controller, msn):
        self.controller = controller
        self.msn = msn
        
        self.whiteList = []
        self.blackList = []
        
        self.uni = dl.open("/usr/local/lib/unicorn/libunicorn.so") #confirmar
        self.listLoader(self.controller.userEmail,  'rfatao@hotmail.com')

        #NOTIFICATION START
        self.notifications = []
        self.tray = self.controller.trayIcon.getNotifyObject()
        self.pixbuf = self.controller.theme.getImage('userPanel')
        #NOTIFICATION STOP
        aspects.with_wrap(self.wrapBuddyNotification, self.controller.conversationManager.newConversation)

    def listLoader(self,  account,  contactEmail):
        ret = self.askUnicorn(account,  contactEmail)
        deixa = True
        # Passar um FOR ou algo do tipo ateh acabar a bendita contact list
        
        if ret == True:
            #append na lista de white
            self.whiteList.append(contactEmail)
        else:
            #append na lista de white
            self.blackList.append(contactEmail)
        
        self.whiteList.sort()
        self.blackList.sort()

    def isKiduxAllowed(self,  stringEmail):
        #TODO: consultar unicorn para pendentes
        if (not stringEmail in self.blackList) and (stringEmail in self.whiteList):
        # nao esta na lista negra mas esta na lista de liberados
            return True
        else:
        # else, esta na "lista" de pendentes ou desconhecido
            return False

    #TODO: inside function wrapBuddyNotification, wait for fixes in aspects library
    #def wrapBuddyNotification(self, *args, **kwargs):
    def wrapBuddyNotification(self, *args, **kwargs):
        target = args[2]
        if self.isKiduxAllowed(target):
            retval = yield aspects.proceed(*args, **kwargs)            
            yield aspects.return_stop(retval)
        else:
            #NOTIFICATION START
            email = target
            contact = email
            text = str(email)+"\nNão Autorizado"
            self.notifyByAuthorizedStatus(contact, "Emesene", text, 'Conversation', email)
            #NOTIFICATION STOP

    #NOTIFICATION START
    def notifyByAuthorizedStatus(self, contact, title, text, execute = '', data = None):
        notification = pynotify.Notification(title, text, attach = self.tray)
        notification.set_icon_from_pixbuf(self.pixbuf)
        if self.controller.trayIcon and isinstance(self.controller.trayIcon.tray, gtk.StatusIcon):
            tray = self.controller.trayIcon.tray
            try:
                notification.attach_to_status_icon(tray)
            except:
                print "cant set geometry hints on libnotify plugin"
        try:
            notification.show()
        except gobject.GError:
            print "can't display notification" # TODO, retry?
            return
        notification.connect('closed', self.on_notify_close)
        self.notifications.append(notification)

####################################################
    def askUnicorn(self, arg1,  arg2):
        ret = self.uni.call("pythonIM", arg1,  arg2)
        #################################
        print '@@@@@@@@@@@@'
        print 'o valor de ret eh: '
        print ret
        print '@@@@@@@@@@@@'

        if ret == 1:            
            return True
        else:
            return False
####################################################

    #TODO: change name of function on_notify_close
    def on_notify_close(self, n):
        if n in self.notifications:
            self.notifications.remove(n)
    #NOTIFICATION STOP
    
    

